﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RENIT.DragNDropUpload.Extensibility;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint;

namespace RENIT.DragNDropUpload.Utils
{
    public class XsltListViewWebPartAdapter : IWebPartAdapter
    {

        public bool IsWebPartSupported(System.Web.UI.WebControls.WebParts.WebPart webPart)
        {
            return webPart is XsltListViewWebPart;
        }

        public UploadTargetData GetTargetData(System.Web.UI.WebControls.WebParts.WebPart webPart, IEnumerable<IWebPartAdapter> otherAdapters)
        {
            UploadTargetData data = null;
            var lvwp = webPart as XsltListViewWebPart;
            if (lvwp.ChromeState == System.Web.UI.WebControls.WebParts.PartChromeState.Normal)
            {
                using (var guard = lvwp.WebId == Guid.Empty ? WebGuard.GetCurrent() : WebGuard.OpenWebOfCurrentSite(lvwp.WebId))
                {
                    if (guard.IsDocumentLibrary(lvwp.ListName) && guard.CurrentUserCanUploadFilesInto(lvwp.ListName))
                    {
                        data = GetTargetData(lvwp);
                    }
                }
            }
            return data;
        }

        private static UploadTargetData GetTargetData(XsltListViewWebPart webPart)
        {
            return new UploadTargetData
            {
                Title = webPart.Title,
                WPCellID = "MSOZoneCell_WebPart" + webPart.Qualifier,
                SiteId = SPContext.Current.Site.ID,
                WebID = webPart.WebId == Guid.Empty ? SPContext.Current.Web.ID : webPart.WebId,
                ListID = new Guid(webPart.ListName),
                FolderUrl = GetFolderUrl(webPart),
            };
        }

        private static string GetFolderUrl(XsltListViewWebPart webPart)
        {
            var reader = webPart.GetObjectReader();
            return reader.GetStringField("_rootFolder");
        }

    }
}
